import { Ref, useRef } from 'react';
import { OneModal } from '@/components/one-ui';
import { IOneModalRef } from '@/pages/type';
import { AreaNumManageAPI } from '../common/type';
import { UpdateFormColumns } from '../mconfig';
import { Form, message } from 'antd';
import { useRequest } from 'umi';
import { getBaseUrl } from '@/services/urlconst';
import { requestFunComponFiex, getCompanyID, getPosIDs, getUserDepID, getUserID } from '@/utils';
/**
 * 定义行政区域新增和编辑模态框
 * @param param0
 * @returns
 */
const AreaNumUpdateView: React.FC<AreaNumManageAPI.IUpdateViewContextType> = ({
  checkedRows,
  onRequest,
  onClose,
}) => {
  const areaNumUpdateRef: Ref<IOneModalRef> = useRef(null);
  const [areaNumUpdateForm] = Form.useForm();

  /* 关闭弹窗 */
  const onCloseModal = () => {
    if (areaNumUpdateRef) {
      if (areaNumUpdateRef.current) {
        if (areaNumUpdateRef.current.onModalCancel) {
          areaNumUpdateRef.current.onModalCancel();
        }
      }
    }
  };

  const onSubmitForm = () => {
    areaNumUpdateForm.validateFields().then((res) => {
      if (res) {
        const params = {
          id: checkedRows?.id,
          versionNum: checkedRows?.versionNum ?? 0,
          modifyerID: checkedRows?.id ? getUserID() : null,
          modifyPositionID: checkedRows?.id ? getPosIDs() : null,
          modifyDepartmentID: checkedRows?.id ? getUserDepID() : null,
          modifyCompanyID: checkedRows?.id ? getCompanyID() : null,
          ...res,
        };
        updateRequestFun.run(params);
      }
    });
  };

  /** 表格数据请求处理业务 */
  const updateRequestFun = useRequest(
    (record: Record<string, any>) => {
      const addURL = `${getBaseUrl()}/areaNumController/add`;
      const editURL = `${getBaseUrl()}/areaNumController/edit`;
      let params = {
        ...record,
      };
      if (record?.id) {
        return requestFunComponFiex('PUT', editURL, params);
      } else {
        return requestFunComponFiex('POST', addURL, params);
      }
    },
    {
      manual: true,
      onSuccess: (res: any) => {
        if (res && res?.msgFlag) {
          message.success(res?.msg);
          onRequest();
          onCloseModal();
          // onRequest = () => {
          //   onCloseModal;
          // };
        } else {
          message.error(res?.msg);
        }
      },
    },
  );

  return (
    <OneModal
      open={true}
      ref={areaNumUpdateRef}
      title={checkedRows && checkedRows?.id ? '编辑区域' : '新增区域'}
      getContainer={false}
      bodyStyle={{ padding: '5px 0px' }}
      okButtonProps={{
        loading: updateRequestFun.loading,
      }}
      onCancel={onClose}
      onOk={onSubmitForm}
      destroyOnClose={true}
    >
      <UpdateFormColumns
        checkedRows={checkedRows}
        areaNumUpdateForm={areaNumUpdateForm}
      />
    </OneModal>
  );
};

export { AreaNumUpdateView };
